﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IBatisNet.DataMapper;

namespace StateGrid.User
{
    /// <summary>
    /// 提供用户相关的数据库操作。
    /// </summary>
    public class UserManageDAO
    {
        public enum UserOrderType
        {
            NONE,
            BY_NAME,
            BY_IP,
            BY_ROLE
        }

        private ISqlMapper sqlMapper = Mapper.Instance();
        /// <summary>
        /// 用户数目。
        /// </summary>
        /// <returns></returns>
        public int CountUsers()
        {
            int result = sqlMapper.QueryForObject<int>("SelectUserCount", null);
            return result;
        }
        /// <summary>
        /// 添加新用户。
        /// </summary>
        /// <param name="username">用户名，此用户名不能已存在。</param>
        /// <param name="password">密码</param>
        /// <param name="ipLimit">ip绑定地址</param>
        /// <param name="role">用户角色</param>
        /// <param name="functionModularIDs">用户被赋予的权限列表（使用function_modular表的id组成一个数组。数组中的元素即被赋予的权限。）</param>
        /// <returns>是否插入成功。此方法采用事务处理，所以插入失败不会在数据库产生垃圾数据。</returns>
        public bool AddUser(String username, String password, String ipLimit, UserRole role, IList<String> functionModularIDs)
        {
            User newUser = new User();
            newUser.name = username;
            newUser.password = password;
            newUser.ipLimit = ipLimit;
            newUser.role = role;
            bool result;

            //事务处理：插入失败，事务回滚
            try
            {
                sqlMapper.BeginTransaction();
                //插入user表
                sqlMapper.Insert("InsertUser", newUser);
                //循环插入user_function表
                foreach (String modularId in functionModularIDs)
                {
                    IDictionary<String, String> dic = new Dictionary<String, String>();
                    dic.Add("username", username);
                    dic.Add("functionid", modularId);
                    sqlMapper.Insert("InsertUserFunctionRelation", dic);
                }
                sqlMapper.CommitTransaction();
                result = true;
            }
            catch
            {
                sqlMapper.RollBackTransaction();
                result = false;
            }

            return result;
        }
        /// <summary>
        /// 通过User类添加一个用户。
        /// 添加的User对象grantedModulars属性中，只关心id，而不关心name。
        /// </summary>
        /// <param name="user">需要添加的用户。</param>
        /// <returns>添加是否成功。</returns>
        public bool AddUser(User user)
        {
            List<String> functionIds = new List<string>();
            foreach (FunctionModular mod in user.grantedModulars)
                functionIds.Add(mod.id);
            return AddUser(user.name, user.password, user.ipLimit, user.role, functionIds);
        }
        /// <summary>
        /// 获取数据库中的所有用户信息。
        /// </summary>
        /// <returns>数据库中所有用户。</returns>
        public IList<User> GetAllUsers()
        {
            return sqlMapper.QueryForList<User>("SelectAllUsers", null);
        }
        /// <summary>
        /// 获取设定范围内的用户信息。
        /// </summary>
        /// <param name="start">跳过的结果数</param>
        /// <param name="end">结果列表的最长长度</param>
        /// <param name="orderType">排序依据。</param>
        /// <returns>一定范围内的用户信息。</returns>
        public IList<User> GetSomeUsers(int start, int end, UserOrderType orderType)
        {

            IDictionary<String, int> para = new Dictionary<String, int>();
            para.Add("start", start);
            para.Add("end", end);

            //按名字排序
            if (orderType == UserOrderType.BY_NAME)
            {
                return sqlMapper.QueryForList<User>("SelectSomeUsersByName", para);
            }
            //按IP排序
            else if (orderType == UserOrderType.BY_IP)
            {
                return sqlMapper.QueryForList<User>("SelectSomeUsersByIp", para);
            }
            //按角色排序
            return sqlMapper.QueryForList<User>("SelectSomeUsersByRole", para);
        }
        /// <summary>
        /// 根据用户名查找用户。
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>用户不存在，返回null</returns>
        public User GetUserByName(String username)
        {
            User user = sqlMapper.QueryForObject<User>("SelectUserByName", username);
            if (null == user)
            {
                return null;
            }

            IList<FunctionModular> list = user.grantedModulars;
            if (null == list)
            {
                return user;
            }

            SortedList<int, FunctionModular> sort = new SortedList<int, FunctionModular>();
            foreach (FunctionModular temp in list)
            {
                sort.Add(temp.list_order, temp);
            }

            list.Clear();
            //将篇目模块排序后的给用户
            user.grantedModulars = sort.Values;
            return user;
        }

        public FunctionModular GetFuncModByID(String functionId)
        {
            return sqlMapper.QueryForObject<FunctionModular>("SelectFunctionModularByID", functionId);
        }
        /// <summary>
        /// 根据用户名删除用户。
        /// 此删除为物理删除，删除之后不可恢复。
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>删除是否成功</returns>
        public bool DeleteUserByName(String username)
        {
            bool result;
            //事务处理
            try
            {
                //首先删除和此用户被赋予的功能模块。
                sqlMapper.BeginTransaction();
                sqlMapper.Delete("DeleteUserFunctionRelationByUsername", username);

                //然后删除用户信息。
                sqlMapper.Delete("DeleteUserByName", username);
                sqlMapper.CommitTransaction();
                result = true;
            }
            catch
            {
                sqlMapper.RollBackTransaction();
                result = false;
            }
            return result;
        }
        /// <summary>
        /// 根据用户名修改用户信息。
        /// 必须传入已存在的用户名。其他参数即为修改的值。
        /// </summary>
        /// <param name="username">用户名，必须已存在</param>
        /// <param name="password">密码</param>
        /// <param name="ipLimit">ip绑定</param>
        /// <param name="role">角色</param>
        /// <param name="functionModularIDs">拥有权限的功能模块</param>
        /// <returns>修改是否成功。</returns>
        public bool UpdateUserByName(String username, String password, String ipLimit, UserRole role, IList<String> functionModularIDs)
        {
            bool result;
            //查看是否存在此用户。
            User u = GetUserByName(username);
            if (u == null)
            {
                Console.WriteLine("Upadate出错：用户不存在");
                //用户不存在
                result = false;
            }
            else
            {
                u.password = password;
                u.ipLimit = ipLimit;
                u.role = role;
                //事务处理
                try
                {
                    sqlMapper.BeginTransaction();
                    //修改User表
                    sqlMapper.Update("UpdateUser", u);

                    //先删除原先的权限，再增加新的权限
                    sqlMapper.Delete("DeleteUserFunctionRelationByUsername", username);
                    if (null != functionModularIDs)
                    {
                        //循环插入user_function表
                        foreach (String modularId in functionModularIDs)
                        {
                            IDictionary<String, String> dic = new Dictionary<String, String>();
                            dic.Add("username", username);
                            dic.Add("functionid", modularId);
                            sqlMapper.Insert("InsertUserFunctionRelation", dic);
                        }
                    }
                    sqlMapper.CommitTransaction();
                    result = true;
                }
                catch
                {
                    sqlMapper.RollBackTransaction();
                    result = false;
                }
            }
            return result;
        }
        /// <summary>
        /// 通过User类修改一个用户。修改依据为用户名。
        /// 修改的User对象grantedModulars属性中，只关心id，而不关心name。
        /// </summary>
        /// <param name="user">需要修改的用户。</param>
        /// <returns>添加是否成功。</returns>
        public bool UpdateUserByName(User user)
        {
            List<String> functionIds = new List<string>();
            if (null != user.grantedModulars)
            {
                foreach (FunctionModular mod in user.grantedModulars)
                    functionIds.Add(mod.id);
            }
            return UpdateUserByName(user.name, user.password, user.ipLimit, user.role, functionIds);
        }


        /// <summary>
        /// 判断用户登录信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static Boolean IsLogin(User user)
        {
            Boolean login = true;
            if (null == user)
            {
                login = false;
            }
            return login;
        }

        /// <summary>
        /// 按照功能获取具有该功能的所有用户
        /// </summary>
        /// <param name="functionID">功能ID</param>
        /// <returns>用户名列表</returns>
        public IList<String> SelectUserByFunction(String functionID)
        {
            return sqlMapper.QueryForList<String>("SelectUserByFunction", functionID);
        }
    }
}
